package DesignModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tiang on 2018/7/10.
 * 观察者模式
 */
public class ObserverModel {
    /**
     * 被观察者，持有一个或多个观察者的列表，在适当时机调用观察者的方法
     */
    static abstract class Subject{
        protected List<Observer> list = new ArrayList<>();
        public void attach(Observer ob){
            list.add(ob);
        }
        public void detach(Observer ob){
            list.remove(ob);
        }
    }

    /**
     * 观察者，当被观察者有动作时会通知观察者，调用观察者对应的方法
     */
    interface Observer{
        void before();
        void after();
    }

    static class Eating extends Subject{
        public void eat(){
            list.forEach(observer -> observer.before());
            System.out.println("I am start eating.");
            list.forEach(observer -> observer.after());
        }
    }

    static class EatingListener implements Observer{

        @Override
        public void before() {
            System.out.println("Remember wash your hands.");
        }

        @Override
        public void after() {
            System.out.println("Remember wash dishes.");
        }
    }
    public static void main(String[] args) {
        Eating eating = new Eating();
        eating.attach(new EatingListener());
        eating.eat();
    }
}
